<?php
/**
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */

namespace app\mobile\controller;

use app\admin\model\FigureAvatar;
use app\admin\model\FigureBrokerageLog;
use app\admin\model\FigureBrokerageSet;
use app\admin\model\FigureCompositeAvatar;
use app\admin\model\FigureResourcesProfit;
use app\admin\model\FigureUser;
use app\admin\model\FigureVoiceTwin;

use think\facade\Log;

use app\admin\model\FigureResourcesGoods;
use app\admin\model\FigureResourcesOrder;
use app\BaseController;
use think\App;
use think\facade\Db;
use OSS\OssClient;

/**
 *
 * @author Administrator
 *
 */
class ResourcesOrder extends BaseController
{
    public function createOrder()
    {
        $request = $this->request;
        $param = $request->param();
        $figureResourcesGoodsModel = new FigureResourcesGoods();
        $figureResourcesGoodsInfo = $figureResourcesGoodsModel->where(['id' => $param['id'], 'status' => 1])->find();
        $user = FigureUser::where('id', $param['uid'])->find();
        if (empty($user)) {
            return result(- 1, '用户不存在');
        }
        if ($figureResourcesGoodsInfo) {
            if ($figureResourcesGoodsInfo['uid'] == $param['uid']) {
                 if ($figureResourcesGoodsInfo['type'] == 1 ) {
                     return result(-1, '此形象是自己生成形象');
                 } else {
                     return result(-1, '此形象是自己生成声音');
                 }
             }
             $priceArray = json_decode($figureResourcesGoodsInfo['price'],true);
             $dateByIndex = array_column($priceArray,null,'index');
           if ($dateByIndex[$param['day_index']]['price'] != $param['price']) {
               return result(-1, '支付金额有误');
           }

            $data = [
                'figure_resources_goods_id' => $param['id'],
                'uid' => $param['uid'],
                'sell_uid' => $figureResourcesGoodsInfo['uid'],
                'price' => $param['price'],
                'figure_avatar_id' => $figureResourcesGoodsInfo['figure_avatar_id'],
                'composite_figure_avatar_id' => $figureResourcesGoodsInfo['composite_figure_avatar_id'],
                'figure_voice_twin_id' => $figureResourcesGoodsInfo['figure_voice_twin_id'],
                'type' => $figureResourcesGoodsInfo['type'],
                'create_time' => time(),
                'log_no' => getPayNo('FR'),
                'status' => 1,
                'effective_day' => $dateByIndex[$param['day_index']]['day']
            ];
          /*  $date = getResourcesTime();
            $dateByIndex = array_column($date,null,'index');
            $data['effective_day'] = $dateByIndex[$param['index']]['day'];*/

            $figureResourcesOrderModel = new FigureResourcesOrder();
            $figureResourcesOrderModel->insert($data);
            $data['name'] = '购买资产';
            return result(0, '购买成功', $data['log_no']);
        } else {
            return result(-1, '已下架');
        }
    }

    public function orderList()
    {
        $request = $this->request;
        $param = $request->param();
        $order = 'fro.create_time';
        $where[] = ['fro.status', '=', 2];
        /*   $where[] = ['fa.delete_time', '=', null];
           $where[] = ['fca.delete_time', '=', null];
           $where[] = ['fat.delete_time', '=', null];*/

        if (! empty(input('year'))) {
            $time = input('year').'-01-01';
            $endTime = strtotime(input('year') . '-12-31');
            if (! empty(input('month'))) {
                $time = input('year').'-'.input('month').'-01';
                $endTime = strtotime("+1 month", strtotime($time));;
            }

            $where[] = ['fro.create_time', '>', strtotime($time)];
            $where[] = ['fro.create_time', '<', $endTime];

        }

        if (isset($param['type']) && !empty($param['type'])) {
            if ($param['type'] == 1) {
                $where[] = ['fro.type', '=', $param['type']];
            } elseif ($param['type'] == 2) {
                $where[] = ['fro.type', '=', $param['type']];
            } elseif ($param['type'] == 3) {
                $where[] = ['fro.type', '=', $param['type']];
            } elseif ($param['type'] == 4) { // 标准形象和高级形象
                $where[] = ['fro.type', 'in', [1, 2]];
            }
        }
        if (isset($param['order_type']) && $param['order_type'] == 1) {
            $where[] = ['fro.uid', '=', $param['uid']];
        } else {
            $where[] = ['fro.sell_uid', '=', $param['uid']];
        }
        $figureResourcesOrderModel = new FigureResourcesOrder();
        $pindex = max(1, intval(input('page')));
        $psize = empty($param['psize']) ? 10 : intval($param['psize']);
        $total = $figureResourcesOrderModel->alias("fro")
            ->leftJoin("figure_user fu", "fro.uid = fu.id")
            ->leftJoin("figure_user fus", "fro.sell_uid = fus.id")
            ->leftJoin("figure_resources_goods frg", "fro.figure_resources_goods_id = frg.id")
            ->leftJoin("figure_avatar fa", "fro.figure_avatar_id = fa.id")
            ->leftJoin("figure_composite_avatar fca", "fro.composite_figure_avatar_id = fca.id")
            ->leftJoin("figure_voice_twin fat", "fro.figure_voice_twin_id = fat.id")
            ->where($where)->count();
        if ($total) {
            $list = $figureResourcesOrderModel->alias("fro")
                ->leftJoin("figure_user fu", "fro.uid = fu.id")
                ->leftJoin("figure_user fus", "fro.sell_uid = fus.id")
                ->leftJoin("figure_resources_goods frg", "fro.figure_resources_goods_id = frg.id")
                ->leftJoin("figure_avatar fa", "fro.figure_avatar_id = fa.id")
                ->leftJoin("figure_composite_avatar fca", "fro.composite_figure_avatar_id = fca.id")
                ->leftJoin("figure_voice_twin fat", "fro.figure_voice_twin_id = fat.id")
                ->field('fro.*,
                  fu.id as fu_id,fu.avatar as fu_avatar,fu.nickname as fu_nickname,
                   fus.id as fus_sell_id,fus.avatar as fus_sell_avatar,fus.nickname as fus_sell_nickname,
                    frg.title as frg_title, frg.id as frg_id,
                    fa.id as fa_id,fa.name as fa_name,fa.type as  fa_type,fa.video_url as fa_video_url , fa.video_cover  as fa_video_cover,fa.image_url as fa_image_url ,fa.video_backgroud_image as fa_video_backgroud_image ,fa.video_backgroud_color as fa_video_backgroud_color ,    
                    fca.id as fca_id,fca.name as fca_name,fca.url as fca_url,
               fat.id as fat_id, fat.name as fat_name,fat.voice_urls as fat_voice_urls,fat.train_mode as fat_train_mode,fat.media_url as fat_media_url')
                ->where($where)
                ->order($order, 'desc')
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();

        } else {
            $list = [];
        }
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    public static function orderCallback($log_no, $price)
    {
        Db::startTrans();

        try {
            $redis = new \Redis();
            $password = isset(config('redis')["password"]) ? config('redis')["password"] : '';
            $port = empty(config('redis')["port"]) ? '6379' : config('redis')["port"];
            $redis->connect('127.0.0.1', $port);
            if (!empty($password)) {
                $redis->auth($password);
            }

            $figureResourcesOrderModel = new FigureResourcesOrder();
            $log = $figureResourcesOrderModel->where('log_no', $log_no)->find();
            if ($log['status'] == 2) {
                exit();
            }
            $redisLog = $redis->get("figureResourcesOrder-" . $log_no);


            if ($redisLog) {
                exit();
            }
            $redis->set("figureResourcesOrder-" . $log_no, 1);
            $redis->persist("figureResourcesOrder-" . $log_no);
            $log['price'] = (float)$log['price'];
            $price = (float)$price;
            if (bccomp($log['price'], $price, 2) != 0) {
                Log::error("Member update_member  交易异常   记录金额" . $log['money'] . "  支付金额" . $price);
                exit();
            }
            $sell_uid = $log['sell_uid'];
            $uid = $log['uid'];
            //计算佣金
            $release = sysconfig('release');
            $data = ['status' => 2, 'update_time' => time()];
            $total_commission = 0;
            $data['one_superior_commisson_ratio'] = 0;
            $data['one_superior_commisson'] = 0;
            $data['tow_superior_commisson_ratio'] = 0;
            $data['tow_superior_commisson'] = 0;
            if ($release['release_platform_points']) {  // 全部分佣
                $data['total_commission_ratio'] = $release['release_platform_points'];
                $total_commission = bcdiv(bcmul($log['price'], $release['release_platform_points'], 2), 100, 2);
                // 分销
                if ($total_commission > 0) {
                    $setting = FigureBrokerageSet::where('id', 1)->find();
                    if (isset($setting) && $setting['is_open'] == 1) { // 分销开启
                        $commission = array();
                        $pid = array();
                        switch ($setting['is_level']) {
                            case 1:
                                // 从全部佣金中抽取 分佣
                                $commission[0] = bcdiv(bcmul($total_commission, $setting['oneLevel'], 2), 100, 2);
                                $data['one_superior_commisson_ratio'] = $setting['oneLevel'];
                                $data['one_superior_commisson'] = $commission[0];
                                break;
                            case 2:
                                // 从全部佣金中抽取分佣
                                $commission[0] = bcdiv(bcmul($total_commission, $setting['oneLevel'], 2), 100, 2);
                                $data['one_superior_commisson_ratio'] = $setting['oneLevel'];
                                $data['one_superior_commisson'] = $commission[0];
                                $commission[1] = bcdiv(bcmul($total_commission, $setting['twoLevel'], 2), 100, 2);
                                $data['tow_superior_commisson_ratio'] = $setting['twoLevel'];
                                $data['tow_superior_commisson'] = $commission[1];
                                break;
                            default:
                                $commission = array();
                                $data['one_superior_commisson_ratio'] = $setting['oneLevel'];
                                $data['one_superior_commisson'] = 0;
                                $data['tow_superior_commisson_ratio'] = $setting['twoLevel'];
                                $data['tow_superior_commisson'] = 0;
                                break;
                        }
                        $pid[0] = FigureUser::where('id', $uid)->value('pid');
                        if (!empty($pid[0])) {
                            $pid[1] = FigureUser::where('id', $pid[0])->value('pid');
                        }
                        if (!empty($pid[1])) {
                            $pid_three = FigureUser::where('id', $pid[1])->value('pid');
                            if (!empty($pid_three)) {
                                $pid[2] = $pid_three;
                            }
                        }
                        $brokerageLog = [];
                        if (!empty($commission) && !empty($pid)) {
                            $t = time();
                            foreach ($commission as $k => $v) {
                                if ($v < 0.01 || empty($pid[$k])) {
                                    continue;
                                }
                                $brokerage = FigureBrokerageLog::where([
                                    'log_no' => $log_no,
                                    'type' => 4,
                                    'pid' => $pid[$k],
                                    'uid' => $uid,

                                ])->find();
                                if (!empty($brokerage)) {
                                    continue;
                                }
                                $pUser = FigureUser::where('id', $pid[$k])->find();
                                if ($pUser) {
                                    $brokerageLog[] = [
                                        'log_no' => $log_no,
                                        'type' => 4,
                                        'pid' => $pid[$k],
                                        'uid' => $uid,
                                        'total' => $price,
                                        'money' => $v,
                                        'create_time' => $t,
                                        'commission_level' => $k+1
                                    ];
                                    $pUser->save([
                                        'brokerage' => Db::raw('brokerage+' . $v)
                                    ]);
                                }
                            }
                        }
                        if (!empty($brokerageLog)) {
                            $brokerage = new FigureBrokerageLog();
                            $brokerage->saveAll($brokerageLog);
                        }
                    }
                }

            }
            $data['commission_profit'] = bcsub($price, $total_commission, 2);
            // 平台佣金的 总佣金 - 代理分佣
            if ($log['effective_day']>0){
                $effective_time = time()+$log['effective_day'] * 86400;
            }else{
                $effective_time = 0;
            }

            $data['effective_time'] = $effective_time;
            $data['platform_commission'] = bcsub(bcsub($total_commission, $data['one_superior_commisson'], 2), $data['tow_superior_commisson'], 2);
            $figureResourcesOrderModel->where('log_no', $log_no)->update($data);

            // 把数据放到对应的表中

            switch ($log['type']) {
                case 1: // 高级形象
                    $Model = new FigureAvatar();
                    $findId = $log['figure_avatar_id'];
                    break;

                case 3:
                    $Model = new FigureVoiceTwin();
                    $findId = $log['figure_voice_twin_id'];
                    break;
                default:
                    $Model = new FigureAvatar();
                    break;
            }
            $info = $Model->where(['id' => $findId])->find()->toArray();
            $info['uid'] = $uid;
            $info['ascription_type'] = 2;
            $info['order_id'] = $log['id'];
            $info['create_time'] = time();
            $info['update_time'] = time();
            $info['effective_time'] = $effective_time;
            unset($info['id']);
            $Model->insert($info);

            $FigureUserModel = new FigureUser();
            $FigureUserModel->where('id', $sell_uid)->inc('brokerage', $data['commission_profit'])->update();
            $FigureResourcesProfitModel = new FigureResourcesProfit();
            $figureResourcesProfitData = [
                'uid' => $sell_uid,
                'order_id' => $log['id'],
                'figure_resources_goods_id' => $log['figure_resources_goods_id'],
                'order_price' => $log['price'],
                'platform_profit' => $data['platform_commission'],
                'one_superior_commisson' => $data['one_superior_commisson'],
                'tow_superior_commisson' => $data['tow_superior_commisson'],
                'create_time' => time(),
                'user_profit' => $data['commission_profit'],
                'figure_avatar_id' => $log['figure_avatar_id'],
                'composite_figure_avatar_id' => $log['composite_figure_avatar_id'],
                'figure_voice_twin_id' => $log['figure_voice_twin_id'],
                'type' => $log['type'],
            ];
            $FigureResourcesProfitModel->insert($figureResourcesProfitData);
            $redis->del("figureResourcesOrder-" . $log_no);

            $figureResourcesGoodsModel = new FigureResourcesGoods();
            $figureResourcesGoodsModel->where(['id' => $log['figure_resources_goods_id']])
                ->inc('sell_number')->inc('sell_money', $log['price'])->inc('sell_money', $data['commission_profit'])->update();
            // 关闭连接
            $redis->close();
            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            Log::error("Member update_member 失败   error:" . $e->getLine() . '--->' . $e->getMessage());
        }
    }


    public function test()
    {
        $request = $this->request;
        $param = $request->param();
        $log_no = $param['log_no'];
        $price = $param['price'];
        Db::startTrans();
      try {
            $redis = new \Redis();
            $password = isset(config('redis')["password"]) ? config('redis')["password"] : '';
            $port = empty(config('redis')["port"]) ? '6379' : config('redis')["port"];
            $redis->connect('127.0.0.1', $port);
            if (!empty($password)) {
                $redis->auth($password);
            }

            $figureResourcesOrderModel = new FigureResourcesOrder();
            $log = $figureResourcesOrderModel->where('log_no', $log_no)->find();
            if ($log['status'] == 2) {
                exit();
            }
            $redisLog = $redis->get("figureResourcesOrder-" . $log_no);


          /* if ($redisLog) {
                exit();
            }*/
            $redis->set("figureResourcesOrder-" . $log_no, 1);
            $redis->persist("figureResourcesOrder-" . $log_no);
            $log['price'] = (float)$log['price'];
            $price = (float)$price;
            if (bccomp($log['price'], $price, 2) != 0) {
                Log::error("Member update_member  交易异常   记录金额" . $log['money'] . "  支付金额" . $price);
                exit();
            }
            $sell_uid = $log['sell_uid'];
            $uid = $log['uid'];
            //计算佣金
            $release = sysconfig('release');
            $data = ['status' => 2, 'update_time' => time()];
            $total_commission = 0;
            $data['one_superior_commisson_ratio'] = 0;
            $data['one_superior_commisson'] = 0;
            $data['tow_superior_commisson_ratio'] = 0;
            $data['tow_superior_commisson'] = 0;
            if ($release['release_platform_points']) {  // 全部分佣
                $data['total_commission_ratio'] = $release['release_platform_points'];
                $total_commission = bcdiv(bcmul($log['price'], $release['release_platform_points'], 2), 100, 2);
                // 分销
                if ($total_commission > 0) {
                    $setting = FigureBrokerageSet::where('id', 1)->find();
                    if (isset($setting) && $setting['is_open'] == 1) { // 分销开启
                        $commission = array();
                        $pid = array();
                        switch ($setting['is_level']) {
                            case 1:
                                // 从全部佣金中抽取 分佣
                                $commission[0] = bcdiv(bcmul($total_commission, $setting['oneLevel'], 2), 100, 2);
                                $data['one_superior_commisson_ratio'] = $setting['oneLevel'];
                                $data['one_superior_commisson'] = $commission[0];
                                break;
                            case 2:
                                // 从全部佣金中抽取分佣
                                $commission[0] = bcdiv(bcmul($total_commission, $setting['oneLevel'], 2), 100, 2);
                                $data['one_superior_commisson_ratio'] = $setting['oneLevel'];
                                $data['one_superior_commisson'] = $commission[0];
                                $commission[1] = bcdiv(bcmul($total_commission, $setting['twoLevel'], 2), 100, 2);
                                $data['tow_superior_commisson_ratio'] = $setting['twoLevel'];
                                $data['tow_superior_commisson'] = $commission[1];
                                break;
                            default:
                                $commission = array();
                                $data['one_superior_commisson_ratio'] = $setting['oneLevel'];
                                $data['one_superior_commisson'] = 0;
                                $data['tow_superior_commisson_ratio'] = $setting['twoLevel'];
                                $data['tow_superior_commisson'] = 0;
                                break;
                        }
                        $pid[0] = FigureUser::where('id', $uid)->value('pid');
                        if (!empty($pid[0])) {
                            $pid[1] = FigureUser::where('id', $pid[0])->value('pid');
                        }
                        if (!empty($pid[1])) {
                            $pid_three = FigureUser::where('id', $pid[1])->value('pid');
                            if (!empty($pid_three)) {
                                $pid[2] = $pid_three;
                            }
                        }
                        $brokerageLog = [];
                        if (!empty($commission) && !empty($pid)) {
                            $t = time();
                            foreach ($commission as $k => $v) {
                                if ($v < 0.01 || empty($pid[$k])) {
                                    continue;
                                }
                                $brokerage = FigureBrokerageLog::where([
                                    'log_no' => $log_no,
                                    'type' => 4,
                                    'pid' => $pid[$k],
                                    'uid' => $uid
                                ])->find();
                                if (!empty($brokerage)) {
                                    continue;
                                }
                                $pUser = FigureUser::where('id', $pid[$k])->find();
                                if ($pUser) {
                                    $brokerageLog[] = [
                                        'log_no' => $log_no,
                                        'type' => 3,
                                        'pid' => $pid[$k],
                                        'uid' => $uid,
                                        'total' => $price,
                                        'money' => $v,
                                        'create_time' => $t
                                    ];
                                    $pUser->save([
                                        'brokerage' => Db::raw('brokerage+' . $v)
                                    ]);
                                }
                            }
                        }
                        if (!empty($brokerageLog)) {
                            $brokerage = new FigureBrokerageLog();
                            $brokerage->saveAll($brokerageLog);
                        }
                    }
                }

            }
            $data['commission_profit'] = bcsub($price, $total_commission, 2);
            // 平台佣金的 总佣金 - 代理分佣

            $data['platform_commission'] = bcsub(bcsub($total_commission, $data['one_superior_commisson'], 2), $data['tow_superior_commisson'], 2);
            $figureResourcesOrderModel->where('log_no', $log_no)->update($data);

            // 把数据放到对应的表中

            switch ($log['type']) {
                case 1: // 高级形象
                    $Model = new FigureAvatar();
                    $findId = $log['figure_avatar_id'];
                    break;
                case 2:  // 标准形象
                    $Model = new FigureCompositeAvatar();
                    $findId = $log['composite_figure_avatar_id'];
                    break;
                case 3:
                    $Model = new FigureVoiceTwin();
                    $findId = $log['figure_voice_twin_id'];
                    break;
                default:
                    $Model = new FigureAvatar();
                    break;
            }
            $info = $Model->where(['id' => $findId])->find()->toArray();
            $info['uid'] = $sell_uid;
            $info['ascription_type'] = 2;
            $info['order_id'] = $log['id'];
            unset($info['id']);

            $Model->insert($info);

            $FigureUserModel = new FigureUser();
            $FigureUserModel->where('id', $sell_uid)->inc('brokerage', $data['commission_profit'])->update();
            $FigureResourcesProfitModel = new FigureResourcesProfit();
            $figureResourcesProfitData = [
                'uid' => $sell_uid,
                'order_id' => $log['id'],
                'figure_resources_goods_id' => $log['figure_resources_goods_id'],
                'order_price' => $log['price'],
                'platform_profit' => $data['platform_commission'],
                'one_superior_commisson' => $data['one_superior_commisson'],
                'tow_superior_commisson' => $data['tow_superior_commisson'],
                'create_time' => time(),
                'user_profit' => $data['commission_profit'],
                'figure_avatar_id' => $log['figure_avatar_id'],
                'composite_figure_avatar_id' => $log['composite_figure_avatar_id'],
                'figure_voice_twin_id' => $log['figure_voice_twin_id'],
                'type' => $log['type'],
            ];

            $FigureResourcesProfitModel->insert($figureResourcesProfitData);
            $redis->del("figureResourcesOrder-" . $log_no);

            $figureResourcesGoodsModel = new FigureResourcesGoods();
            $figureResourcesGoodsModel->where(['id' => $log['figure_resources_goods_id']])
                ->inc('sell_number')->inc('sell_money', $log['price'])->inc('sell_money', $data['commission_profit'])->update();
            // 关闭连接
            $redis->close();
            Db::commit();
            echo '成功';
       } catch (\Exception $e) {
            Db::rollback();
            Log::error("Member update_member 失败   error:" . $e->getLine() . '--->' . $e->getMessage());
        }

    }




}